from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http import HttpResponse


from verifications import contants



class RegisterImageCodeView(APIView):

    def get(self,request,image_code_id):
        # 创建图片和验证码
        text,image = captcha.generate_captcha()
        # 通过redis进行保存验证码
        print(text)

        redis_conn = get_redis_connection('code')

        redis_conn.setex('img_%s'%image_code_id,contants.IMAGECODEEXPIRE,text)
        # 将图片返回
        #注意,图片是二进制,我们通过HttpResponse返回
        return HttpResponse(image,content_type='image/jpeg')

"""
需求:
"""

from verifications.serilizers import RegisterSmsCodeSerializer
from libs.yuntongxun.sms import CCP
from rest_framework.response import Response


class RegisterSmsCodeAPIView(APIView):
    def get(self,request,mobile):
        query_params = request.query_params

        serializer = RegisterSmsCodeSerializer(data=query_params)
        serializer.is_valid()

        from random import randint
        sms_code = '%06d'%randint(0,999999)
        print(sms_code)


        # CCP().send_template_sms(mobile,[sms_code,5],1)
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)

        redis_conn = get_redis_connection('code')

        redis_conn.setex('sms_%s'%mobile,300,sms_code)

        return Response({'msg':'ok'})


